package net.suncapper.wcss.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import net.suncapper.wcss.common.JsonResponse;
import net.suncapper.wcss.model.domain.Product;
import net.suncapper.wcss.mapper.ProductMapper;
import net.suncapper.wcss.model.domain.ProductImage;
import net.suncapper.wcss.model.domain.Sku;
import net.suncapper.wcss.model.dto.PageDTO;
import net.suncapper.wcss.model.dto.ProductDTO;
import net.suncapper.wcss.model.vo.ProductVO;
import net.suncapper.wcss.service.IProductImageService;
import net.suncapper.wcss.service.IProductService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import net.suncapper.wcss.service.ISkuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * <p>
 * 衣服款式表 服务实现类
 * </p>
 *
 * @author ztr
 * @since 2025-11-10
 */
@Transactional(rollbackFor = Exception.class)
@Service
public class ProductServiceImpl extends ServiceImpl<ProductMapper, Product> implements IProductService {
    @Autowired
    private IProductImageService productImageService;
    @Autowired
    private ISkuService skuService;
    @Override
    public JsonResponse productSave(ProductDTO productDTO) {
        //验证唯一

            super.save(productDTO);
            List<Sku> Skus = productDTO.getSkus().stream().map(sku -> new Sku().setName(sku).setProductId(productDTO.getId())).collect(Collectors.toList());
            List<ProductImage> images = productDTO.getUrls().stream().map(url -> new ProductImage().setPath(url).setProductId(productDTO.getId())).collect(Collectors.toList());
            skuService.saveBatch(Skus);
            productImageService.saveBatch(images);
        return JsonResponse.success(true);
    }

    @Override
    public Page<ProductVO> pagelist(ProductDTO productDTO, PageDTO pageDTO) {
        Page<ProductVO> page = new Page<>(pageDTO.getPageNo(), pageDTO.getPageSize());
        page= baseMapper.pageList(page,productDTO);
        page.getRecords().stream().forEach(productVO -> {productVO.setSku(skuService.list(Wrappers.<Sku>lambdaQuery().eq(Sku::getProductId, productVO.getId())));
            productVO.setImages(productImageService.list(Wrappers.<ProductImage>lambdaQuery().eq(ProductImage::getProductId,productVO.getId())));
         });
        return page;
    }
}
